<template>
  <div class="box">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model.trim.trim="queryParams.parameter.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model.trim="queryParams.parameter.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model.trim="queryParams.parameter.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option label="启用" :value="'1'"></el-option>
              <el-option label="禁用" :value="'0'"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" v-for="(val,i) of permiList" :key="i">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleDeal({},val)"
              v-if="val.funcCode == 'Add'"
            >{{ val.funcName }}</el-button>
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleDeal({},val)"
              v-if="val.funcCode == 'Edit'"
            >{{ val.funcName }}</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDeal({},val)"
              v-if="val.funcCode == 'Delete'"
            >{{ val.funcName }}</el-button>
            <el-button
              type="info"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-if="val.funcCode == 'ImportExcel'"
            >{{ val.funcName }}</el-button>
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-if="val.funcCode == 'ExprotExcel'"
            >{{ val.funcName }}</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" border>
          <el-table-column :resizable="false" type="selection" width="50" align="center"/>
          <el-table-column :resizable="false" label="用户编号" align="center" prop="userCode"  width="180"/>
          <el-table-column :resizable="false" label="用户姓名" align="center" prop="userName" :show-overflow-tooltip="true"  width="120"/>
          <el-table-column :resizable="false" label="归属部门" align="center" prop="deptName"  width="220" />
          <el-table-column :resizable="false" label="性别" align="center" prop="status">
            <template slot-scope="scope">
              {{scope.row.sex == 1 ? '男' : '女'}}
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="固定电话" align="center" prop="telNum"  width="180" />
          <el-table-column :resizable="false" label="移动电话" align="center" prop="mobileNum"  width="180" />
          <el-table-column :resizable="false" label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-switch
                v-model.trim="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="220"
          >
            <template slot-scope="scope">
              <div class="deal-column" v-for="(val,i) of permiList" :key="i">
                <el-button
                  type="text"
                  icon="el-icon-view"
                  size="mini"
                  @click="handleDeal(scope.row,val)"
                  v-if="val.funcCode == 'View'"
                >{{ val.funcName }}</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleDeal(scope.row,val)"
                  v-if="val.funcCode == 'Edit'"
                >{{ val.funcName }}</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeal(scope.row,val)"
                  v-if="val.funcCode == 'Delete'"
                >{{ val.funcName }}</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-key"
                  @click="handleResetPwd(scope.row)"
                  v-if="val.funcCode == 'Reset'"
                >{{ val.funcName }}</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="dealType == 'View'">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户编码" prop="userCode">
              <el-input v-model.trim="form.userCode" placeholder="请输入用户编码" :disabled="dealType != 'Add'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model.trim="form.userName" placeholder="请输入用户姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptCode">
              <treeselect v-model.trim="form.deptCode" :options="deptOptions" :show-count="true" placeholder="请选择归属部门"  :disabled="dealType == 'View'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="固定电话" prop="telNum">
              <el-input v-model.trim="form.telNum" placeholder="请输入固定电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="移动电话" prop="mobileNum">
              <el-input v-model.trim="form.mobileNum" placeholder="移动电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model.trim="form.sex" placeholder="请选择">
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
        </el-row>
        <el-row>
          <el-col :span="dealType == 'Add'? 12 : 24">
            <el-form-item label="身份证号" prop="userIdentify">
              <el-input v-model.trim="form.userIdentify" placeholder="请输入身份证号" maxlength="18" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dealType == 'Add'" label="用户密码" prop="passwd">
              <el-input v-model.trim="form.passwd" placeholder="请输入用户密码" type="password" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model.trim="form.email" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="dealType != 'View'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="重置密码" :visible.sync="pwdOpen" width="550px" append-to-body :close-on-click-modal="false">
      <el-form ref="pwdForm" :model="user" :rules="rules" label-width="80px">
        <el-form-item label="新密码" prop="newPasswd">
          <el-input v-model.trim="user.newPasswd" placeholder="请输入新密码" type="password"  show-password/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPasswd">
          <el-input v-model.trim="user.confirmPasswd" placeholder="请确认密码" type="password"  show-password/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitPwd">保存</el-button>
        <el-button size="mini" @click="pwdOpen = false">关闭</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import { listUser, delUser, addUser, updateUser, checkDetails } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { pagePermission } from '@/utils/common.js';
import { getKeys } from "@/api/login";
const sm2 = require('sm-crypto').sm2
const cipherMode = 1

export default {
  name: "User",
  components: { Treeselect },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPasswd !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      // 公钥
      pubkeys: undefined,
      // 选中行
      select_row:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 权限列表
      permiList: [],
      // 操作类型
      dealType: '',
      // 当前页面的code
      menuCode: '',
      // 部门树选项
      deptOptions: [],
      // 是否显示弹出层
      open: false,
      pwdOpen: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      user: {
        newPasswd: undefined,
        confirmPasswd: undefined
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 50,
        parameter:{
          userName: undefined,
          phonenumber: undefined,
          status: undefined,
          deptId: undefined
        },
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        userCode: [
          { required: true, message: "用户编码不能为空", trigger: "blur" }
        ],
        deptCode: [
          { required: true, message: "归属部门不能为空", trigger: "blur" }
        ],
        passwd: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            pattern: /^(?![A-Za-z0-9]+$)(?![a-z0-9\W]+$)(?![A-Za-z\W]+$)(?![A-Z0-9\W]+$)[a-zA-Z0-9\W]{8,}$/,
            message: "密码必须包含8位或8位以上字符、大小写字母、数字、特殊符号(空格除外)",
            trigger: "blur"
          }
        ],
        mobileNum: [
          { required: true, message: "移动电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        sex: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        userIdentify: [
          {
            pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入正确的身份证号",
            trigger: "blur"
          }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        newPasswd: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          {
            pattern: /^(?![A-Za-z0-9]+$)(?![a-z0-9\W]+$)(?![A-Za-z\W]+$)(?![A-Z0-9\W]+$)[a-zA-Z0-9\W]{8,}$/,
            message: "密码必须包含8位或8位以上字符、大小写字母、数字、特殊符号(空格除外)",
            trigger: "blur"
          }
        ],
        confirmPasswd: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    pwdOpen(val) {
      if(!val){
        this.resetForm("pwdForm");
        this.user = {
          newPasswd: undefined,
          confirmPasswd: undefined
        }
      }
    }
  },
  created() {
    this.getList();
    this.getPermissionList();
  },
  methods: {
    getPermissionList(){
      let name = this.$route.name;
      let allMenu = JSON.parse(localStorage.getItem('allMenu')) 
      pagePermission(name,allMenu,this);
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(res => {
        if(res.status == 200){
          this.userList = res.data.list;
          this.total = res.data.total;
        }else if(res.status == 102){
          this.userList = [];
          this.total = 0;
        }
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        // this.deptOptions = response.data;
        this.initTree(response.data)
      });
    },
    // 部门树结构格式化
    initTree( tree ){
      tree.forEach(item=>{
        item.id = item.value;
        if( item.children && item.children.length > 0 ){
          this.initTree(item.children)
        }
      })
      this.deptOptions = tree;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "禁用";
      this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=>{
          let param = {
            parameter: {
              sysUser: {
                userCode: row.userCode,
                status: row.status
              }
            }
          }
          return updateUser(param);
        }).then((response) => {
          if(response.status == 200){
            this.msgSuccess("修改成功");
            this.getList();
          }else if(response.status == 101){
            this.msgError(response.errors[0].message);
            row.status = row.status === "0" ? "1" : "0";
          }
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userCode: undefined,
        deptCode: undefined,
        userName: undefined,
        passwd: undefined,
        telNum: undefined,
        mobileNum: undefined,
        sex: '1',
        status: "1",
        userIdentify: '',
        ext1: '1',  // 是否值班
        ext2: '1',  // 是否主班
        ext3: '1',  // 1:水情值班；2：网络值班；3：带班领导
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageIndex: 1,
        pageSize: 50,
        parameter:{
          userName: undefined,
          phonenumber: undefined,
          status: undefined,
          deptId: undefined
        },
      }
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userCode);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.select_row = selection;
    },
    /** 查询性别 */
    checkDetail(data) {
      checkDetails(data).then(response => {
        if(data == "SYS_USER_SEX") {
          this.sexOptions = response.data
        } else {
          this.roleOptions = response.data
        }
      });
    },
    /** 权限操作 */
    handleDeal(row,val){
      if(val.funcCode == 'Edit'){
        this.dealType = 'Edit';
        this.handleUpdate(row)
      }else if(val.funcCode == 'Reset'){
        this.dealType = 'Reset';
        this.handleResetPwd(row)
      }else if(val.funcCode == 'Delete'){
        this.dealType = 'Delete';
        this.handleDelete(row)
      }else if(val.funcCode == 'View'){
        this.dealType = 'View';
        this.handleView(row)
      }else if(val.funcCode == 'Add'){
        this.dealType = 'Add';
        this.handleAdd()
      }
    },
    /** 获取公钥 */
    getKeys(){
      getKeys().then((res)=>{
        if(res.status == 200){
          this.pubkeys = res.data;
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.checkDetail("SYS_USER_SEX");
      this.checkDetail("SYS_SQDUTY_TYPE");
      this.open = true;
      this.title = "添加用户";
      this.dealType = 'Add';
      this.open = true;
      this.getKeys();
    },
    handleView(row){
      this.reset();
      this.getTreeselect();
      this.checkDetail("SYS_USER_SEX");
      this.checkDetail("SYS_SQDUTY_TYPE");
      this.form = {...row};
      this.title = "查看用户";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.checkDetail("SYS_USER_SEX");
      this.checkDetail("SYS_SQDUTY_TYPE");
      if(row && row.userCode){
        this.form = {...row}
      }else{
        this.form = this.select_row[0]
      }
      this.open = true;
      this.title = "修改用户";
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.getKeys();
      this.form = {...row};
      this.pwdOpen = true;
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.dealType == 'Edit') {
            let param = {
              parameter: {
                sysUser: this.form
              }
            }
            updateUser(param).then(response => {
              if(response.status == 200){
                this.msgSuccess("修改成功");
                this.getList();
                this.open = false;
              }else if(response.status == 101){
                this.msgError(response.errors[0].message);
              }
            });
          } else if(this.dealType == 'Add'){
            let sysUser = { ...this.form };
            sysUser.passwd = "04"+sm2.doEncrypt(sysUser.passwd, this.pubkeys, cipherMode);
            let param = {
              parameter: {
                sysUser: sysUser
              }
            }
            addUser(param).then(response => {
              if(response.status == 200){
                this.msgSuccess("新增成功");
                this.getList();
                this.open = false;
              }else if(response.status == 101){
                this.msgError(response.errors[0].message);
              }
            });
          } else if(this.dealType == 'View'){
            this.open = false;
          }
        }
      });
    },
    /** 重置密码提交操作 */
    submitPwd() {
      this.$refs["pwdForm"].validate(valid => {
        if(valid) {
          let param = {
            parameter: {
              sysUser: {
                userCode: this.form.userCode,
                passwd: "04"+sm2.doEncrypt(this.user.newPasswd, this.pubkeys, cipherMode)
              }
            }
          }
          updateUser(param).then((response) => {
            if(response.status == 200){
              this.msgSuccess("修改成功");
              this.pwdOpen = false;
            }else if(response.status == 101){
              this.msgError(response.errors[0].message);
            }
          })
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let userIds = row.userCode || this.ids;
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        if( !(row && row.userCode )){
          userIds = userIds.join(',');
        }
        let param = {
          parameter: {
            userCode: userIds
          }
        }
        return delUser(param);
      }).then((res) => {
        if(res.status == 200){
          this.getList();
          this.msgSuccess("删除成功");
        }else if(res.status == 101){
          this.msgError(res.errors[0].message);
        }
      }).catch(()=>{

      })
    },
  }
};
</script>